package com.ch.playandroid.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2

fun ViewPager2.setFragmentAdapter(fragment: Fragment, block: ViewPager2Adapter.() -> Unit) {
    val adapter = ViewPager2Adapter(fragment)
    adapter.block()
    this.adapter = adapter
}

fun ViewPager2.setFragmentAdapter(activity: FragmentActivity, block: ViewPager2Adapter.() -> Unit) {
    val adapter = ViewPager2Adapter(activity)
    adapter.block()
    this.adapter = adapter
}

fun ViewPager2.setFragmentAdapter(
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle,
    block: ViewPager2Adapter.() -> Unit
) {
    val adapter = ViewPager2Adapter(fragmentManager, lifecycle)
    adapter.block()
    this.adapter = adapter
}

class ViewPager2Adapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    constructor(fragment: Fragment) : this(fragment.childFragmentManager, fragment.lifecycle)

    constructor(activity: FragmentActivity) : this(
        activity.supportFragmentManager,
        activity.lifecycle
    )

    private var itemCount = 0

    private lateinit var createFragment: (Int) -> Fragment

    override fun getItemCount(): Int {
        return itemCount
    }

    fun count(count: Int) {
        itemCount = count
    }

    override fun createFragment(position: Int): Fragment {
        return createFragment.invoke(position)
    }

    fun createFragment(createFragment: (Int) -> Fragment) {
        this.createFragment = createFragment
    }
}